package com.dmap.admin.controller.backgroundv2;

import com.dmap.admin.bo.backgroundv2.UserV2Bo;
import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.UserV2Param;
import com.dmap.admin.controller.backgroundv2.param.UserV2SelectParam;
import com.dmap.admin.po.LoginLog;
import com.dmap.admin.po.User;
import com.dmap.admin.service.backgroundv2.IdentifyingCodeService;
import com.dmap.admin.service.backgroundv2.LoginLogService;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.admin.units.SortList;
import com.dmap.admin.vo.backgroundv2.RecordNumAndUserV2Vo;
import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 04/05/18
 * \* Description:
 * \
 */
@Api(value = "V2用户管理", description = "background/V2用户管理")
@Controller
@RequestMapping(value = "/background/pmpd-admin-server/v2/user/")
public class UserV2Controller {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserV2Service userV2Service;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private IdentifyingCodeService identifyingCodeService;

    @ResponseBody
    @ApiOperation(value = "新增 user",
            notes = "1. 必填： 手机号码handphone, 用户账号account, 密码password, userType, " +
                    "creatorId, creatorAccount, verificationCode; " +
                    "2. 返回userId;")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public BaseVo insert(@RequestBody UserV2Param param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getHandphone()) || StringUtils.isBlank(param.getAccount())
                || StringUtils.isBlank(param.getPassword()) || StringUtils.isBlank(param.getCreatorAccount())
                || param.getUserType() == null || param.getUserType() == 0
                || StringUtils.isBlank(param.getCreatorId()) || !StringUtils.isNumeric(param.getCreatorId())
                || Long.valueOf(param.getCreatorId()).equals(0L)
                || StringUtils.isBlank(param.getVerificationCode())) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        User selectUser = userV2Service.validateAccountOrHandphoneIsExist(param.getAccount(), param.getHandphone());
        if (selectUser != null) {
            //如果是已存在并删除的用户则直接更改其状态
            if (selectUser.getDeleteStatus() == AdminConstant.DELETE_STATUS_DELETED) {
                param.setId(selectUser.getId().toString());
                param.setEditorId(param.getCreatorId());
                param.setEditorAccount(param.getCreatorAccount());
                param.setDeleteStatus(AdminConstant.DELETE_STATUS_NORMAL);
                baseVo = this.update(param);
                return baseVo;
            }
            baseVo.setCode(AdminConstant.RESPONSE_USER_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_USER_ERROR_MSG);
            return baseVo;
        }
        String value = identifyingCodeService.getIdentifyingCode(param.getHandphone());
        if (StringUtils.isBlank(value)) {
            baseVo.setCode(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_MSG);
            return baseVo;
        }
        if (!value.equals(param.getVerificationCode())) {
            baseVo.setCode(AdminConstant.RESPONSE_CODE_WRONG_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_CODE_WRONG_ERROR_MSG);
            return baseVo;
        }
        User user = userV2Service.insertUser(param);
        if (user == null) {
            baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
            return baseVo;
        }
        baseVo.setData(user.getId().toString());
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "修改 user",
            notes = "1. 必填： id, 手机号码handphone, 用户账号account, userType, editorId, " +
                    " editorAccount;")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseVo update(@RequestBody UserV2Param param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getId()) || !StringUtils.isNumeric(param.getId())
                || StringUtils.isBlank(param.getHandphone()) || StringUtils.isBlank(param.getAccount())
                || Long.valueOf(param.getId()).equals(0L) || StringUtils.isBlank(param.getEditorAccount())
                || param.getUserType() == null || param.getUserType() == 0
                || StringUtils.isBlank(param.getEditorId()) || !StringUtils.isNumeric(param.getEditorId())
                || Long.valueOf(param.getEditorId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        if (StringUtils.isNotBlank(param.getVerificationCode())) {
            String value = identifyingCodeService.getIdentifyingCode(param.getHandphone());
            if (StringUtils.isBlank(value)) {
                baseVo.setCode(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_CODE);
                baseVo.setMsg(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_MSG);
                return baseVo;
            }
            if (!value.equals(param.getVerificationCode())) {
                baseVo.setCode(AdminConstant.RESPONSE_CODE_WRONG_ERROR_CODE);
                baseVo.setMsg(AdminConstant.RESPONSE_CODE_WRONG_ERROR_MSG);
                return baseVo;
            }
        }
        boolean success;
        try {
            success = userV2Service.updateUser(param);
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            baseVo.setCode(AdminConstant.RESPONSE_USER_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_USER_ERROR_MSG);
            return baseVo;
        }
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "批量删除 user", notes = "1. 必填： id;")
    @RequestMapping(value = "delete/deleteByIdList", method = RequestMethod.POST)
    public BaseVo deleteByIdList(@RequestBody List<String> idList) {
        BaseVo baseVo = new BaseVo();
        if (CollectionUtils.isEmpty(idList)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        List<Long> deleteList = new ArrayList<>();
        for (String id : idList) {
            if (StringUtils.isNotBlank(id) && StringUtils.isNumeric(id) && !Long.valueOf(id).equals(0L)) {
                deleteList.add(Long.valueOf(id));
            } else {
                baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
                return baseVo;
            }
        }
        boolean success = userV2Service.deleteByIdList(deleteList);
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_DELETE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_DELETE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据用户id查询用户", notes = "1. 必填： id;")
    @RequestMapping(value = "select/selectById", method = RequestMethod.GET)
    public BaseVo selectById(@RequestParam String id) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(id) || !StringUtils.isNumeric(id) || Long.valueOf(id).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        User user = userV2Service.selectById(Long.valueOf(id));
        UserV2Bo userV2Bo = null;
        if (user != null) {
            userV2Bo = new UserV2Bo(user);
            LoginLog loginLog = loginLogService.selectLastLogByUserId(user.getId());
            if (loginLog != null) {
                userV2Bo.setLastLoginTime(loginLog.getCreateTime());
            }
            int recordNumber = loginLogService.countByUserId(user.getId());
            userV2Bo.setLoginTimes(recordNumber);
        }
        baseVo.setData(userV2Bo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据参数查询用户，和模糊查询、排序是一个接口",
            notes = "1. 必填： companyId, userType; " +
                    "2. 必填：pageIndex(>=1), pageSize(>=1); " +
                    "3. 返回user列表; ")
    @RequestMapping(value = "select/selectByExample", method = RequestMethod.POST)
    public BaseVo selectByExample(@RequestBody UserV2SelectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)
                || (param.getUserType() != AdminConstant.USER_TYPE_COMPANY_ADMIN &&
                (param.getUserType() != AdminConstant.USER_TYPE_DEPARTMENT_ADMIN ||
                        (StringUtils.isBlank(param.getDepartmentId()) || !StringUtils.isNumeric(param.getDepartmentId())
                                || Long.valueOf(param.getDepartmentId()).equals(0L))))
                || param.getPageIndex() == null || param.getPageSize() == null
                || param.getPageIndex() < 1 || param.getPageSize() < 1) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        int recordNum = userV2Service.countByUserV2SelectParam(param);
        List<UserV2Bo> boList = new ArrayList<>();
        if (recordNum > 0) {
            List<User> list = userV2Service.selectByUserV2SelectParam(param);
            for (User user : list) {
                UserV2Bo userV2Bo = null;
                if (user != null) {
                    userV2Bo = new UserV2Bo(user);
                    LoginLog loginLog = loginLogService.selectLastLogByUserId(user.getId());
                    if (loginLog != null) {
                        userV2Bo.setLastLoginTime(loginLog.getCreateTime());
                    }
                    int loginTimes = loginLogService.countByUserId(user.getId());
                    userV2Bo.setLoginTimes(loginTimes);
                    boList.add(userV2Bo);
                }
            }
        }
        if (param.getSortField() != null && CollectionUtils.isNotEmpty(boList) && boList.size() > 1
                && param.getSortField().equalsIgnoreCase(AdminConstant.SORT_BY_LAST_LOGIN_TIME)) {
            SortList<UserV2Bo> sortList = new SortList<>();
            if (param.getOrder() == AdminConstant.ORDER_BY_ASC) {
                sortList.sortByMethod(boList, "getLastLoginTime", false);
            } else if (param.getOrder() == AdminConstant.ORDER_BY_DESC) {
                sortList.sortByMethod(boList, "getLastLoginTime", true);
            }
        }
        RecordNumAndUserV2Vo returnVo = new RecordNumAndUserV2Vo(recordNum, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据account或handphone查找用户",
            notes = "1.必填(2选1)： 用户账号account 或者 手机号handphone; " +
                    "2.返回用户信息;")
    @RequestMapping(value = "select/selectByAccountOrHandphone", method = RequestMethod.GET)
    public BaseVo selectByAccountOrHandphone(@RequestParam String param) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(param)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        User user = userV2Service.selectByAccountOrHandphone(param);
        if (user != null) {
            UserV2Bo bo = new UserV2Bo(user);
            baseVo.setData(bo);
        }
        return baseVo;
    }

}